<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.phone"
        placeholder="手机号"
        style="width: 200px;"
        class="filter-item"
        clearable
        @keyup.enter.native="handleFilter"
      />
      <el-select
        v-model="listQuery.company"
        filterable
        class="filter-item"
        clearable
        placeholder="请选择加油站"
        @keyup.enter.native="handleFilter"
      >
        <el-option v-for="item in cooperation" :label="item.company" :value="item.company"/>
      </el-select>
      <!-- <el-input v-model="listQuery.title" placeholder="手机号" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" /> -->
      <el-select
        v-model="listQuery.type"
        placeholder="类型"
        clearable
        style="width: 120px"
        class="filter-item"
      >
        <el-option label="加油站" value="1" aria-checked=""/>
        <!-- <el-option
          label="修理站"
          value="2"
        />-->
        <el-option label="加气站" value="3"/>
        <!-- <el-option
          label="总公司"
          value="4"
        />-->
      </el-select>
      <el-select
        v-model="listQuery.state"
        placeholder="状态"
        clearable
        style="width: 120px"
        class="filter-item"
      >
        <el-option label="开启" value="0" aria-checked=""/>
        <el-option label="关闭" value="1"/>
      </el-select>
      <!-- <el-select v-model="listQuery.type" :placeholder="$t('table.type')" clearable class="filter-item" style="width: 130px">
        <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name+'('+item.key+')'" :value="item.key" />
      </el-select>
      <el-select v-model="listQuery.sort" style="width: 140px" class="filter-item" @change="handleFilter">
        <el-option v-for="item in sortOptions" :key="item.key" :label="item.label" :value="item.key" />
      </el-select>-->
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >{{ $t('table.search') }}</el-button>
      <!-- <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >{{ $t('table.add') }}</el-button>-->
      <!-- <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        {{ $t('table.export') }}
      </el-button>
      <el-checkbox v-model="showReviewer" class="filter-item" style="margin-left:15px;" @change="tableKey=tableKey+1">
        {{ $t('table.reviewer') }}
      </el-checkbox>-->
    </div>
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="tableData"
      border=""
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="序号" prop="id" align="center" width="50">
        <template slot-scope="scope">{{ scope.$index + 1 }}</template>
      </el-table-column>
      <el-table-column label="发货人" min-width align="center">
        <template slot-scope="scope">{{ scope.row.name }}</template>
      </el-table-column>
      <el-table-column label="发货人电话" min-widthh align="center">
        <template slot-scope="scope">{{ scope.row.phone }}</template>
      </el-table-column>
      <el-table-column label="省" width="" align="center">
        <template slot-scope="scope">{{ scope.row.province }}</template>
      </el-table-column>
      <el-table-column label="市" min-width align="center">
        <template slot-scope="scope">{{ scope.row.city }}</template>
      </el-table-column>
      <el-table-column label="区" min-width align="center">
        <template slot-scope="scope">{{ scope.row.country }}</template>
      </el-table-column>
      <el-table-column v-if="isAdmin" prop="detailedAddress" label="详细地址" align="center" width=""/>
      <el-table-column v-if="isAdmin" prop="created" label="创建时间" align="center" width=""/>
      <el-table-column
        label="操作"
        align="center"
        width="170px"
        class-name="small-padding fixed-width"
        fixed="right"
      >
        <template slot-scope="scope">
          <!-- <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button> -->
          <el-button type="danger" size="mini" @click="del(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      top="2vh"
      width="720px"
    >
      <el-form
        ref="temp"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="110px"
        style="width: 550px; margin-left:50px;"
      >
        <el-form-item label="姓名" prop="company">
          <el-input v-model="temp.company" style="width:422px"/>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="temp.phone" style="width:422px"/>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="temp.type">
            <el-radio :label="1">发货地址</el-radio>
            <el-radio :label="2">收货地址</el-radio>
          </el-radio-group>
        </el-form-item>
        <provinceData ref="provinceData" :temp="temp" @listen="getProvince" @ifValid="ifValid"/>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{ $t('table.cancel') }}</el-button>
        <el-button type="primary" @click="createData()">{{ $t('table.confirm') }}</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border="" fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel"/>
        <el-table-column prop="pv" label="Pv"/>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">{{ $t('table.confirm') }}</el-button>
      </span>
    </el-dialog>
    <el-dialog :visible.sync="dialogCode" title="站点二维码" style="text-align:center">
      <!-- <qrCode :codeVal="codeVal"></qrCode> -->
      <img :src="imageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import permission from "@/directive/permission/index.js"; // 权限判断指令
import checkPermission from "@/utils/permission"; // 权限判断函数

import { fetchPv, updateCooperation } from "@/api/article";
import { address_list, del_address, goods_edit } from "@/api/goods";
import { cooperationUnBind } from "@/api/user";

import waves from "@/directive/waves"; // Waves directive
import { parseTime } from "@/utils";
import Pagination from "@/components/Pagination"; // Secondary package based on el-pagination
import qrCode from "@/components/qrcode";
import { Loading } from "element-ui";
import provinceData from "@/components/province";
import { MessageBox, Message } from "element-ui";

export default {
  name: "ComplexTable",
  components: { Pagination, qrCode, provinceData },
  directives: { waves, permission },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: "success",
        draft: "info",
        deleted: "danger"
      };
      return statusMap[status];
    },
    typeFilter(type) {
      if (type == 1) {
        return "加油站";
      } else if (type == 2) {
        return "修理站";
      } else if (type == 3) {
        return "加气站";
      } else if (type == 4) {
        return "总公司";
      } else {
        return "";
      }
    },
    stateFilter(state) {
      if (state == 1) {
        return "关闭";
      } else if (state == 0) {
        return "开启";
      } else {
        return "";
      }
    }
  },
  data() {
    return {
      agentId: "agentId",
      editPhone: true,
      allAgent: [],
      imageUrl: "",
      codeVal: "",
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        phone: "",
        name: "",
        type: "",
        sort: "+id",
        state: "",
        company: ""
      },
      payTypeOptions: [
        { id: 1, value: "京东支付" },
        { id: 2, value: "浦发支付" }
      ],
      stateOptions: [{ id: 0, value: "开启" }, { id: 1, value: "关闭" }],
      typeOptions: [
        { id: 1, value: "加油站" },
        // { id: 2, value: '修理站' },
        { id: 3, value: "加气站" }
        // { id: 4, value: '总公司' }
      ],
      importanceOptions: [1, 2, 3],
      sortOptions: [
        { label: "ID Ascending", key: "+id" },
        { label: "ID Descending", key: "-id" }
      ],
      statusOptions: ["published", "draft", "deleted"],
      showReviewer: false,
      temp: {
        name: "",
        phone: "",
        id: "",
        company: "",
        type: 1,
        longitude: "",
        latitude: "",
        address: "",
        city: "",
        ownerPhone: "",
        price: "",
        remark: "",
        // gasPrice: "",
        receive: "",
        accountNo: "",
        bankAcountName: "",
        state: 0,
        status: 0,
        provinceCode: "",
        cityCode: "",
        areaCode: "",
        agentId: ""
      },
      cooperation: {},

      dialogFormVisible: false,
      dialogCode: false,
      dialogPay: false,
      dialogStatus: "",
      textMap: {
        update: "编辑",
        create: "新增"
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        phone: [{ required: true, message: "请输入电话", trigger: "blur" }],
        company: [
          { required: true, message: "请输入站点名称", trigger: "blur" }
        ],
        type: [{ required: true, message: "请选择类型", trigger: "change" }]
      },
      downloadLoading: false,
      isAdmin: true,
      options: {
        fullscreen: true,
        // spinner: 'el-icon-loading',
        // background: 'rgba(0, 0, 0, 0.7)',
        text: "加载中..."
      },
      tableData: []
    };
  },
  created() {
    this.getList();
  },
  methods: {
    detail(row) {
      console.log(row);
      this.$router.push({
        path: "/cooperationDetail",
        query: {
          relationId: row.id,
          relationType: 1,
          currentMoney: row.currentMoney,
          phone: row.phone,
          name: row.name,
          uuid: row.uuid
        }
      });
    },

    getList2() {
      this.listLoading = true;
      getallAgent(this.listQuery).then(res => {
        this.allAgent = res.data;
        console.log(this.allAgent);
      });
    },
    getProvince(data) {
      console.log("0000000000000000000000");
      console.log(data);
      this.temp.provinceCode = data.provinceCode;
      this.temp.cityCode = data.cityCode;
      this.temp.areaCode = data.areaCode;
      this.temp.address = data.address;
    },
    route(row) {
      console.log(row);
      this.$router.push({
        path: "/tradesList",
        query: {
          id: row.uuid
        }
      });
    },

    paySet(row) {
      this.pay = Object.assign({}, row); // copy obj
      console.log(row);
      this.dialogPay = true;
      this.$nextTick(() => {
        this.$refs["pay"].clearValidate();
      });
      this.$refs.provinceData.clearProvinceDate();
    },
    getList() {
      this.listLoading = true;
      address_list(this.listQuery).then(res => {
        this.tableData = res.data.records;
        this.total = res.data.total;
        // Just to simulate the time of the request
        this.listLoading = false;
        //        setTimeout(() => {
        //
        //        }, 1.5 * 1000);
      });
    },
    getCooperationAll() {
      cooperationAll().then(res => {
        this.cooperation = res.data;

        // Just to simulate the time of the request
        this.listLoading = false;
        //        setTimeout(() => {
        //          this.listLoading = false;
        //        }, 1.5 * 1000);
      });
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    handleModifyStatus(row, status) {
      console.log(row);
      console.log(status);
      this.$message({
        message: "操作成功",
        type: "success"
      });
      row.status = status;
    },
    sortChange(data) {
      const { prop, order } = data;
      if (prop === "id") {
        this.sortByID(order);
      }
    },
    sortByID(order) {
      if (order === "ascending") {
        this.listQuery.sort = "+id";
      } else {
        this.listQuery.sort = "-id";
      }
      this.handleFilter();
    },
    resetTemp() {
      this.temp = {
        name: "",
        phone: "",
        id: "",
        company: "",
        type: 1,
        longitude: "",
        latitude: "",
        address: "",
        city: "",
        ownerPhone: "",
        price: "",
        remark: "",
        // gasPrice: "",
        receive: "",
        accountNo: "",
        bankAcountName: "",
        state: 0,
        status: "0",
        provinceCode: "",
        cityCode: "",
        areaCode: "",
        agentId: ""
      };
    },
    handleCreate() {
      this.resetTemp();
      console.log(this.temp);
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.editPhone = false;
      this.$nextTick(() => {
        this.$refs["temp"].clearValidate();
      });
      this.$refs.provinceData.clearProvinceDate();
    },
    ifValid(ifValid) {
      if (ifValid) {
        this.$refs["temp"].validate(valid => {
          if (valid) {
            console.log(this.temp);
            createCooperation(this.temp).then(res => {
              // this.list.unshift(this.temp);
              this.dialogFormVisible = false;
              this.$notify({
                title: "成功",
                message: res.msg,
                type: "success",
                duration: 2000
              });
              this.getList();
            });
          }
        });
      }
    },
    createData() {
      this.$refs.provinceData.submitForm();
      this.$refs["temp"].validate(valid => {
        return valid;
      });
    },
    ifValid(ifValid) {
      if (ifValid) {
        this.$refs["temp"].validate(valid => {
          if (valid) {
            console.log(this.temp);
            edit_owner_address(this.temp).then(res => {
              // this.list.unshift(this.temp);
              this.dialogFormVisible = false;
              this.$notify({
                title: "成功",
                message: res.msg,
                type: "success",
                duration: 2000
              });
              this.getList();
            });
          }
        });
      }
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row); // copy obj
      console.log(row);
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.$refs.provinceData.getCityData();
      this.editPhone = true;
      this.$nextTick(() => {
        this.$refs["temp"].clearValidate();
      });
      this.$refs.provinceData.clearProvinceDate();
    },
    del(row) {
      this.$confirm("此操作将删除该地址 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        const data = {};
        data.addressId = row.id;
        del_address(data).then(res => {
          Message({
            message: res.message || "success",
            type: "success",
            duration: 2 * 1000
          });
          this.getList();
        });
      });
    },

    handleDelete(row) {
      this.$notify({
        title: "成功",
        message: "删除成功",
        type: "success",
        duration: 2000
      });
      const index = this.list.indexOf(row);
      this.list.splice(index, 1);
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData;
        this.dialogPvVisible = true;
      });
    },
    handleDownload() {
      this.downloadLoading = true;
      import("@/vendor/Export2Excel").then(excel => {
        const tHeader = ["timestamp", "title", "type", "importance", "status"];
        const filterVal = [
          "timestamp",
          "title",
          "type",
          "importance",
          "status"
        ];
        const data = this.formatJson(filterVal, this.list);
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: "table-list"
        });
        this.downloadLoading = false;
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === "timestamp") {
            return parseTime(v[j]);
          } else {
            return v[j];
          }
        })
      );
    }
  }
};
</script>
<style>
.pagination-container {
  margin-top: 0px;
  padding-bottom: 0px !important;
}
.fixed-width .el-button--mini {
  width: 70px;
}
</style>

